#!/usr/bin/env python3
"""
简单的HTTP服务器用于开发前端
"""

import http.server
import socketserver
import os
import sys
from urllib.parse import urlparse

class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        # 添加CORS头部
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        super().end_headers()

    def do_OPTIONS(self):
        # 处理预检请求
        self.send_response(200)
        self.end_headers()

    def do_GET(self):
        # 处理SPA路由，所有路径都返回index.html
        if self.path.startswith('/api/'):
            # API请求返回404
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'API endpoint not found')
            return
            
        # 静态文件处理
        if '.' not in os.path.basename(self.path):
            self.path = '/index.html'
        
        return super().do_GET()

def run_server(port=3000):
    """运行开发服务器"""
    
    # 切换到前端目录
    frontend_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(frontend_dir)
    
    # 创建服务器
    handler = CustomHTTPRequestHandler
    
    try:
        with socketserver.TCPServer(("", port), handler) as httpd:
            print(f"🚀 BoLe HR Platform Frontend Server")
            print(f"📂 Serving files from: {frontend_dir}")
            print(f"🌐 Server running at: http://localhost:{port}")
            print(f"📱 Mobile access: http://0.0.0.0:{port}")
            print(f"🔗 API Backend: http://localhost:8000")
            print("Press Ctrl+C to stop the server...")
            
            httpd.serve_forever()
            
    except KeyboardInterrupt:
        print("\n🛑 Server stopped by user")
    except OSError as e:
        if e.errno == 48:  # Address already in use
            print(f"❌ Port {port} is already in use. Try a different port:")
            print(f"   python server.py {port + 1}")
        else:
            print(f"❌ Error starting server: {e}")
    except Exception as e:
        print(f"❌ Unexpected error: {e}")

if __name__ == "__main__":
    port = 3000
    
    # 从命令行参数获取端口
    if len(sys.argv) > 1:
        try:
            port = int(sys.argv[1])
        except ValueError:
            print("Invalid port number. Using default port 3000.")
    
    run_server(port)